<?php
namespace Lonicera\core;
use Lonicera\core\Db;
//require_once _SYS_PATH . 'core/DB.php';
class Model{
	
	public function save(){ //保存操作
		$reflect = new \ReflectionClass($this);
		//只获取PUBLIC字段,这里我们约定的所有字段对应的属性使用PUBLIC修饰符
		$props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC);
		//$props =  json_decode( json_encode( $props),true); //这只是对象转化数组的其中一种
		
		$keyArray = [];
		foreach ($props as $property) {
			//echo $property->getName() . ",";
			$keyArray[] = $property->getName();
		}
		
		
		$sqlTemplate = "INSERT INTO " . $this->getTableNameByPO($reflect) . "(";
		//$keyArray = array_column($props,'name'); //直接组织一维数组
		//dump($keyArray); //可以写个dump,能不能使用主要看是否已经加载
		//exit;
		$keys = implode(',', $keyArray);
		$prepareKeys = implode(',',array_map(function($key){
			return ':' . $key;
		},$keyArray));
		$sqlTemplate = "INSERT INTO " . $this->getTableNameByPO($reflect) . "({$keys}) VALUES ($prepareKeys)";
		
		//echo $sqlTemplate;
		
		$data = [];
		foreach($props as $v){
			$data[$v->name] = $reflect->getProperty($v->name)->getValue($this);
		}
		
		$db = DB::getInstance($GLOBALS['_config']['db']);
		$ret = $db->execute($sqlTemplate, $data);
		
		return $ret;
	}
	
	public function deleteByid(){
		 
	}
	
	public function update(){
		
	}
	
	public function find(){
		
	}
	
	public function buildPrimaryWhere(){
		
	}
	
	public function getRealTableName($tableName, $prefix=''){
		if(!empty($prefix)){
			$realTableName = $prefix."_{$tableName}";
		}elseif(isset($GLOBALS['_config']['db']['prefix']) && !empty($GLOBALS['_config']['db']['prefix'])){
			$realTableName = $GLOBALS['_config']['db']['prefix']."_{$tableName}";
		}
		else{
			$realTableName = $tableName;
		}
		
		return $realTableName;
	}
	
	//PO类的自动生成 直接去数据库里取information_schema库里的User表的元字段(METADATA) 然后根据元数据自动生成类文件
	public function buildPO($tableName, $prefix=''){
		$db = DB::getInstance($GLOBALS['_config']['db']);
		$ret = $db->query('SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME=:TABLENAME',array('TABLENAME'=>$this->getRealTableName($tableName,$prefix)));
		$className = ucfirst($tableName); //此处仅为简单实现,暂不考虑驼峰命名法
		$file = _APP.'model/'.$className.'.php';
		$classString = "<?php \r\nclass $className extends Model{ \r\n>";
		foreach($ret as $key=>$value){
			$classString .="			//{$value['COLUMN_NAME']};";
			if(!empty($value['COLUMN_COMMENT'])){
				$classString .= "			//{$value['COLUMN_COMMENT']};";
			}
			
			$classString .= "\r\n";
		
		}
		$classString .= "}";
		file_put_contents($file,$classString);
	}
	
	public function getTableNameByPO($reflect){   //反射
		//反向降解过程,从类名生成表名 暂不考虑多个单词下的驼峰规则需要考虑命名空间的问题
		return $this->getRealTableName(strtolower($reflect->getShortName()));
	}
}